<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import DataTable from '../components/common/DataTable.vue'

const router = useRouter()

const goHome = () => {
  router.push('/')
}
</script>
<template>
  <div class="container mx-auto px-4 py-8">
    <h2 class="text-2xl font-bold mb-6">业主管理</h2>
    <div class="flex justify-between items-center mb-4">
      <button @click="openCreateModal" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition-all duration-300 transform hover:scale-105">
        <i class="fa fa-plus mr-2"></i>新增业主
      </button>
      <div class="relative">
        <input 
          v-model="searchQuery" 
          @input="debouncedSearch" 
          type="text" 
          placeholder="搜索业主..." 
          class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
      </div>
    </div>
    
    <div class="overflow-x-auto">
      <table class="min-w-full bg-white rounded-lg shadow-md overflow-hidden">
        <thead>
          <tr class="bg-gray-50">
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">业主ID</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">性别</th>     
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">年龄</th>                    
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系方式</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房屋</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
          <tr v-for="owner in filteredOwners" :key="owner.id" class="hover:bg-gray-50 transition-colors duration-200">
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.id }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.name }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.gender }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.age }}</td>                        
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.phone }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ owner.idCard }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ formatDate(owner.createTime) }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm font-medium">
              <button @click="openEditModal(owner)" class="text-indigo-600 hover:text-indigo-900 mr-3 transition-colors duration-200">
                <i class="fa fa-edit mr-1"></i>编辑
              </button>
              <button @click="openBindHouseModal(owner)" class="text-green-600 hover:text-green-900 mr-3 transition-colors duration-200">
                <i class="fa fa-home mr-1"></i>绑定房屋
              </button>
              <button @click="deleteOwner(owner.id)" class="text-red-600 hover:text-red-900 transition-colors duration-200">
                <i class="fa fa-trash mr-1"></i>删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="flex justify-between items-center mt-6">
      <div class="text-sm text-gray-700">
        显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, total) }} 条，共 {{ total }} 条
      </div>
      <div class="flex space-x-1">
        <button 
          :disabled="currentPage === 1" 
          @click="currentPage--" 
          class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-200"
        >
          <i class="fa fa-chevron-left"></i>
        </button>
        <button 
          v-for="page in pageCount" 
          :key="page" 
          :class="{
            'px-3 py-1 border border-blue-500 bg-blue-500 text-white rounded-md': page === currentPage,
            'px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50': page !== currentPage
          }" 
          @click="currentPage = page"
          class="transition-colors duration-200"
        >
          {{ page }}
        </button>
        <button 
          :disabled="currentPage === pageCount" 
          @click="currentPage++" 
          class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-200"
        >
          <i class="fa fa-chevron-right"></i>
        </button>
      </div>
    </div>
    
    <!-- 创建/编辑模态框 -->
    <div v-if="isModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-100 opacity-100">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            {{ isEditing ? '编辑业主信息' : '新增业主' }}
          </h3>
          <button @click="closeModal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="p-6">
          <form @submit.prevent="submitForm">
            <div class="mb-4">
              <label for="name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
              <input 
                type="text" 
                id="name" 
                v-model="formData.name" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >
            </div>              
            <div class="mb-4">
              <label for="gender" class="block text-sm font-medium text-gray-700 mb-1">性别</label>
              <input 
                type="text" 
                id="gender" 
                v-model="formData.gender" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >
            </div>              
            <div class="mb-4">
              <label for="age" class="block text-sm font-medium text-gray-700 mb-1">年龄</label>
              <input 
                type="text" 
                id="age" 
                v-model="formData.age" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >                            
            </div>
            <div class="mb-4">
              <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">联系方式</label>
              <input 
                type="tel" 
                id="phone" 
                v-model="formData.phone" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >
            </div>
            <div class="mb-4">
              <label for="idCard" class="block text-sm font-medium text-gray-700 mb-1">房屋</label>
              <input 
                type="text" 
                id="idCard" 
                v-model="formData.idCard" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >
            </div>
            <div class="mb-4">
              <label for="createTime" class="block text-sm font-medium text-gray-700 mb-1">入住时间</label>
              <input 
                type="text" 
                id="createTime" 
                v-model="formData.createTime" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                required
              >              
            </div>
            <div class="flex justify-end space-x-3 mt-6">
              <button type="button" @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
                取消
              </button>
              <button type="submit" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
                {{ isEditing ? '保存修改' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 绑定房屋模态框 -->
    <div v-if="isBindHouseModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 transform transition-all duration-300 scale-100 opacity-100">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            为 {{ selectedOwner.name }} 绑定房屋
          </h3>
          <button @click="closeBindHouseModal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="p-6">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">选择房屋</label>
            <select 
              v-model="selectedHouseId" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">请选择房屋</option>
              <option v-for="house in availableHouses" :key="house.id" :value="house.id">
                {{ house.buildingNumber }}栋{{ house.unitNumber }}单元{{ house.roomNumber }}室
              </option>
            </select>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button @click="closeBindHouseModal" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
              取消
            </button>
            <button @click="bindHouse" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-colors duration-200">
              绑定房屋
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 提示框 -->
    <div v-if="showToast" class="fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-md shadow-lg transform transition-all duration-500 translate-y-0 opacity-100 flex items-center z-50">
      <i class="fa fa-check-circle mr-2"></i>
      <span>{{ toastMessage }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      owners: [],
      filteredOwners: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      isModalOpen: false,
      isEditing: false,
      formData: {
        id: null,
        name: '',
        phone: '',
        idCard: ''
      },
      isBindHouseModalOpen: false,
      selectedOwner: null,
      availableHouses: [],
      selectedHouseId: '',
      showToast: false,
      toastMessage: ''
    };
  },
  computed: {
    total() {
      return this.filteredOwners.length;
    },
    pageCount() {
      return Math.ceil(this.total / this.pageSize);
    },
    paginatedOwners() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredOwners.slice(start, end);
    }
  },
  created() {
    this.fetchOwners();
    // 创建防抖函数
    this.debouncedSearch = this.debounce(this.searchOwners, 300);
  },
  methods: {
    // 获取业主列表
    async fetchOwners() {
      try {
        const response = await this.$axios.get('/api/owners');
        this.owners = response.data;
        this.filteredOwners = [...this.owners];
      } catch (error) {
        console.error('获取业主列表失败:', error);
        this.showToastMessage('获取业主列表失败', 'error');
      }
    },
    
    // 搜索业主
    searchOwners() {
      if (!this.searchQuery.trim()) {
        this.filteredOwners = [...this.owners];
        return;
      }
      
      const query = this.searchQuery.toLowerCase().trim();
      this.filteredOwners = this.owners.filter(owner => {
        return owner.name.toLowerCase().includes(query) ||
               owner.phone.includes(query) ||
               owner.idCard.includes(query);
      });
      
      // 重置页码
      this.currentPage = 1;
    },
    
    // 打开创建模态框
    openCreateModal() {
      this.isEditing = false;
      this.formData = {
        name: '',
        phone: '',
        idCard: ''
      };
      this.isModalOpen = true;
    },
    
    // 打开编辑模态框
    openEditModal(owner) {
      this.isEditing = true;
      this.formData = {
        id: owner.id,
        name: owner.name,
        phone: owner.phone,
        idCard: owner.idCard
      };
      this.isModalOpen = true;
    },
    
    // 关闭模态框
    closeModal() {
      this.isModalOpen = false;
    },
    
    // 提交表单
    async submitForm() {
      try {
        if (this.isEditing) {
          // 更新业主
          await this.$axios.put(`/api/owners/${this.formData.id}`, this.formData);
          this.showToastMessage('业主信息更新成功');
        } else {
          // 创建业主
          await this.$axios.post('/api/owners', this.formData);
          this.showToastMessage('业主创建成功');
        }
        
        this.closeModal();
        this.fetchOwners();
      } catch (error) {
        console.error('提交表单失败:', error);
        this.showToastMessage('操作失败，请重试', 'error');
      }
    },
    
    // 删除业主
    async deleteOwner(id) {
      if (confirm('确定要删除该业主吗？')) {
        try {
          await this.$axios.delete(`/api/owners/${id}`);
          this.showToastMessage('业主删除成功');
          this.fetchOwners();
        } catch (error) {
          console.error('删除业主失败:', error);
          this.showToastMessage('删除失败，请重试', 'error');
        }
      }
    },
    
    // 打开绑定房屋模态框
    async openBindHouseModal(owner) {
      this.selectedOwner = owner;
      this.selectedHouseId = '';
      
      try {
        // 获取可用房屋列表（已简化，实际可能需要过滤掉已绑定的房屋）
        const response = await this.$axios.get('/api/houses');
        this.availableHouses = response.data;
        this.isBindHouseModalOpen = true;
      } catch (error) {
        console.error('获取房屋列表失败:', error);
        this.showToastMessage('获取房屋列表失败', 'error');
      }
    },
    
    // 关闭绑定房屋模态框
    closeBindHouseModal() {
      this.isBindHouseModalOpen = false;
    },
    
    // 绑定房屋
    async bindHouse() {
      if (!this.selectedHouseId) {
        this.showToastMessage('请选择要绑定的房屋', 'warning');
        return;
      }
      
      try {
        await this.$axios.post(`/api/owners/${this.selectedOwner.id}/houses/${this.selectedHouseId}`);
        this.showToastMessage('房屋绑定成功');
        this.closeBindHouseModal();
        this.fetchOwners();
      } catch (error) {
        console.error('绑定房屋失败:', error);
        this.showToastMessage('绑定失败，请重试', 'error');
      }
    },
    
    // 显示提示消息
    showToastMessage(message, type = 'success') {
      this.toastMessage = message;
      this.showToast = true;
      
      // 设置提示框背景色
      const toastElement = document.querySelector('.fixed.bottom-4.right-4');
      if (toastElement) {
        if (type === 'error') {
          toastElement.classList.remove('bg-green-500');
          toastElement.classList.add('bg-red-500');
        } else if (type === 'warning') {
          toastElement.classList.remove('bg-green-500');
          toastElement.classList.add('bg-yellow-500');
        }
      }
      
      // 3秒后隐藏提示框
      setTimeout(() => {
        this.showToast = false;
      }, 3000);
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    
    // 防抖函数
    debounce(func, delay) {
      let timer = null;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }
  }
};

</script>

<style scoped>
/* 模态框动画 */
.fixed.inset-0.bg-black.bg-opacity-50 {
  transition: opacity 0.3s ease-in-out;
}

.fixed.inset-0.bg-black.bg-opacity-50 > div {
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

/* 表格行悬停效果 */
tbody tr {
  transition: background-color 0.2s ease-in-out;
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease-in-out;
}
</style>  